<template>
  <div ref="chartRef" :style="{ height: height, width: width }"></div>
</template>

<script setup>
import { ref, onMounted, watch, defineProps } from 'vue';
import * as echarts from 'echarts';
import { darkTheme, lightTheme } from './chartThemes';

const props = defineProps({
  chartData: {
    type: Array,
    default: () => []
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  theme: {
    type: String,
    default: 'light'
  }
});

const chartRef = ref(null);
let myChart = null;

const themes = {
  dark: darkTheme,
  light: lightTheme
};

const initChart = () => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value, props.theme === 'dark' ? themes.dark : null);
    setOptions(props.chartData);
  }
};

const setOptions = (data) => {
  if (!myChart) return;
  myChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
      textStyle: {
        color: props.theme === 'dark' ? '#fff' : '#333'
      }
    },
    series: [
      {
        name: '分布',
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['65%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
            borderRadius: 10,
            borderColor: props.theme === 'dark' ? '#000c1d' : '#fff',
            borderWidth: 2
        },
        label: {
          show: false,
        },
        data: data
      }
    ]
  });
};

watch(() => props.chartData, (newData) => {
  if (myChart) {
    setOptions(newData);
  }
});

watch(() => props.theme, (newTheme) => {
    if (myChart) {
        myChart.dispose();
        initChart();
    }
});

onMounted(() => {
  initChart();
});
</script> 